<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.1.1">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.1" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.1.1',
    sidebar: {"position":"left","width":290,"display":"post","offset":12,"onmobile":true,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta property="og:type" content="website">
<meta property="og:title" content="Tianzhi Jia">
<meta property="og:url" content="http://jiatianzhi.com/page/5/index.html">
<meta property="og:site_name" content="Tianzhi Jia">
<meta property="og:locale" content="zh-CN">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Tianzhi Jia">





  
  
  <link rel="canonical" href="http://jiatianzhi.com/page/5/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Tianzhi Jia</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left 
  page-home">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tianzhi Jia</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">PhD student in Beijing Jiaotong University</p>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="Toggle navigation bar">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>Home</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    
      
    

    <a href="/blogs/" rel="section"><i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>Blogs<span class="badge">9</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    
      
    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>Categories<span class="badge">5</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-publications">

    
    
    
      
    

    
      
    

    <a href="/publications/" rel="section"><i class="menu-item-icon fa fa-fw fa-book"></i> <br>Publications</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-projects">

    
    
    
      
    

    
      
    

    <a href="/projects/" rel="section"><i class="menu-item-icon fa fa-fw fa-hand-o-right"></i> <br>Projects</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-contact">

    
    
    
      
    

    
      
    

    <a href="/contact/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>Contact</a>

  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    
  
  

  

  <a href="https://gitee.com/jiatianzhi" class="github-corner" title="Follow me on Gitee" aria-label="Follow me on Gitee" rel="noopener" target="_blank"><svg width="80" height="80" viewbox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a>



    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            
  <section id="posts" class="posts-expand">
    
      

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://jiatianzhi.com/leetcode01/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="贾 添 植">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/touxiang.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tianzhi Jia">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                
                <a href="/leetcode01/" class="post-title-link" itemprop="url">LeetCode 01 两数之和</a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            

            
          </span>

          

          
            
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h4 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h4><p>给定一个整数数组 nums 和一个目标值 target，请你在该数组中找出和为目标值的那 两个 整数，并返回他们的数组下标。</p>
<p>你可以假设每种输入只会对应一个答案。但是，你不能重复利用这个数组中同样的元素。</p>
<h4 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">给定 nums = [2, 7, 11, 15], target = 9 </span><br><span class="line"></span><br><span class="line">因为 nums[0] + nums[1] = 2 + 7 = 9 </span><br><span class="line">所以返回 [0, 1]</span><br></pre></td></tr></table></figure>
<h4 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h4><p>1.同样的元素不能重复使用（也就是不能自己加自己）</p>
<p>2.给定的数组中可能有相同的元素（比如 [3, 3, 4, 4, 5]）</p>
<h4 id="方法一"><a href="#方法一" class="headerlink" title="方法一"></a>方法一</h4><p>思路：通过暴力搜索求解，遍历nums列表中所有的两个元素之和nums[i]和nums[j]，时间复杂度为O(n^2)。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> List</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">twoSum</span><span class="params">(self, nums: List[int], target: int)</span> -&gt; List[int]:</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(len(nums)):</span><br><span class="line">            <span class="keyword">for</span> j <span class="keyword">in</span> range(len(nums)):</span><br><span class="line">                <span class="keyword">if</span> nums[i] + nums[j] == target:</span><br><span class="line">                    <span class="keyword">return</span> [i, j]</span><br><span class="line">                </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">twoSum</span><span class="params">(self, nums: List[int], target: int)</span> -&gt; List[int]:</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(len(nums)):</span><br><span class="line">            <span class="keyword">for</span> j <span class="keyword">in</span> range(len(nums)):</span><br><span class="line">                <span class="keyword">if</span> j &gt; i:</span><br><span class="line">                    <span class="keyword">if</span> nums[i] + nums[j] == target:</span><br><span class="line">                        <span class="keyword">return</span> [i, j]</span><br><span class="line">                    </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">twoSum</span><span class="params">(self, nums: List[int], target: int)</span> -&gt; List[int]:</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(len(nums)):</span><br><span class="line">            <span class="keyword">for</span> j <span class="keyword">in</span> range(len(nums)-(i+<span class="number">1</span>)):</span><br><span class="line">                j = j + (i+<span class="number">1</span>)</span><br><span class="line">                <span class="keyword">if</span> nums[i] + nums[j] == target:</span><br><span class="line">                    <span class="keyword">return</span> [i, j]</span><br><span class="line">                </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">twoSum</span><span class="params">(self, nums: List[int], target: int)</span> -&gt; List[int]:</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(len(nums)):</span><br><span class="line">            <span class="keyword">for</span> j <span class="keyword">in</span> range(i+<span class="number">1</span>, len(nums)):</span><br><span class="line">                <span class="keyword">if</span> nums[i] + nums[j] == target:</span><br><span class="line">                    <span class="keyword">return</span> [i, j]</span><br></pre></td></tr></table></figure>
<p>写这种方法的时候，在第二个for循环时遇到了问题根据注意点1，同样的元素不能重复使用，因此第一次尝试，当输入为[3,2,4]和6时，返回的[0,0]错误，正确应为[1,2]，原因就是同样的元素被重复使用了，最终导致解答错误。第二次尝试，试图不重复利用，加入了判断if j &gt; i，由于浪费了很多步骤导致了超时。第三次尝试，遵循元素不重复使用的原则，第二个for循环我们要找的下标开始数值不是0，而是与i有关，从i+1开始，而且第二个for循环每次的循环次数是变化的，因此加入了for j in range(len(nums)-(i+1)):和j = j + (i+1)分别控制循环次数和开始数值，但是依然超时了。当时可能是脑子坏掉了，忘记了range(i+1, len(nums))这种定义for循环开始数值和循环次数的方式，第四次尝试，通过range(i+1, len(nums))同时解决了循环次数和开始数值的问题。</p>
<h4 id="方法二"><a href="#方法二" class="headerlink" title="方法二"></a>方法二</h4><p>思路：先生成一个下标的列表a，一个一个取出nums中的元素，计算target与取出的元素的差c，将nums与下标的列表a一一对应构成字典b，删除字典b中取出的元素nums[i]，查看差c是否在删除元素后的字典b中。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> List</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">twoSum</span><span class="params">(self, nums: List[int], target: int)</span> -&gt; List[int]:</span></span><br><span class="line">        a = range(len(nums))</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(len(nums)):</span><br><span class="line">            c = target - nums[i]</span><br><span class="line">            b = dict(zip(nums, a))</span><br><span class="line">            <span class="keyword">del</span> b[nums[i]]</span><br><span class="line">            <span class="keyword">if</span> c <span class="keyword">in</span> b:</span><br><span class="line">                <span class="keyword">return</span> [i, b[c]]</span><br><span class="line">            </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">twoSum</span><span class="params">(self, nums: List[int], target: int)</span> -&gt; List[int]:</span></span><br><span class="line">        a = range(len(nums))</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(len(nums)):</span><br><span class="line">            c = target - nums[i]</span><br><span class="line">            b = dict(zip(a, nums))</span><br><span class="line">            <span class="keyword">del</span> b[a[i]]</span><br><span class="line">            <span class="keyword">if</span> c <span class="keyword">in</span> b.values():</span><br><span class="line">                <span class="keyword">return</span> [i, list(b.keys())[list(b.values()).index(c)]]</span><br><span class="line">            </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">twoSum</span><span class="params">(self, nums: List[int], target: int)</span> -&gt; List[int]:</span></span><br><span class="line">        a = range(len(nums))</span><br><span class="line">        b = dict(zip(a, nums))</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(len(nums)):</span><br><span class="line">            c = target - nums[i]</span><br><span class="line">            n = b</span><br><span class="line">            <span class="keyword">del</span> n[a[i]]</span><br><span class="line">            <span class="keyword">if</span> c <span class="keyword">in</span> n.values():</span><br><span class="line">                <span class="keyword">return</span> [i, list(n.keys())[list(n.values()).index(c)]]</span><br></pre></td></tr></table></figure>
<p>写这种方法的时候，第一次尝试出现的问题是，根据注意点2，如果给定的数组中有相同的元素，而字典中的键是不能重复的，所以当输入[3,3]和6时，构成的字典b是{3: 1}，而不是{3: 0, 3: 1}，导致计算错误。想出的解决办法是，构成字典时，让nums充当值，让下标的列表a充当键，因为下标的列表是不可能重复的，这样就解决了上述问题，但是新的问题就来了，如何判断target与取出的元素的差c是否在删除元素后的字典b的值中并找到其对应的键？第二次尝试，通过list(b.values())和list(b.keys())再将字典拆成两个列表，分别是值和键，通过if c in b.values():判断c是否在b中，然后通过list(b.values()).index(c)定位c的下标，再通过list(b.keys())[]找到c对应的键，但是很遗憾，又超时了。分析原因可能是因为每一次循环都要重新构成字典b导致超时，第三次尝试，在for循环前构成字典b，每一次for循环定义一个新的字典n，将b赋给n，后面都是用n来进行操作，这样省去了每次循环构成字典b的运算步骤，最终运行通过。</p>
<h4 id="方法三"><a href="#方法三" class="headerlink" title="方法三"></a>方法三</h4><p>使用哈希的思想，利用Python中list的查询方式，将复杂度降低到O(n)。</p>
<p>一个一个取出nums中的元素nums[i]，计算target与nums[i]的差b，将nums[i]后面的元素构成新的列表c，判断差b是否在列表c中，如果在，返回下标c.index(b) + i + 1。此处运行通过，但时间相对方法二并没有缩短。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> List</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">twoSum</span><span class="params">(self, nums: List[int], target: int)</span> -&gt; List[int]:</span></span><br><span class="line">        i = <span class="number">0</span></span><br><span class="line">        <span class="keyword">while</span> i &lt; len(nums):</span><br><span class="line">            b = target - nums[i]</span><br><span class="line">            c = nums[i+<span class="number">1</span>:]</span><br><span class="line">            <span class="keyword">if</span> b <span class="keyword">in</span> c:</span><br><span class="line">                <span class="keyword">return</span> [i, c.index(b) + i + <span class="number">1</span>]</span><br><span class="line">            i = i + <span class="number">1</span></span><br></pre></td></tr></table></figure>
<h4 id="方法四"><a href="#方法四" class="headerlink" title="方法四"></a>方法四</h4><p>先定义一个空字典d，一个一个取出nums中的元素，其下标为i，元素的值为m，计算target与m的差n，如果n在d中，则返回下标，如果不在，则将m加入到字典中。这样，直到target与我们取出的元素的差在字典中时，就完成了任务。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> List</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">twoSum</span><span class="params">(self, nums: List[int], target: int)</span> -&gt; List[int]:</span></span><br><span class="line">        d = &#123;&#125;</span><br><span class="line">        <span class="keyword">for</span> i, m <span class="keyword">in</span> enumerate(nums):</span><br><span class="line">            n = target - m</span><br><span class="line">            <span class="keyword">if</span> n <span class="keyword">in</span> d:</span><br><span class="line">                <span class="keyword">return</span> [d[n], i] <span class="comment"># 此处顺序不能颠倒，d[n]在前，i在后，因为先加入字典d中的，是下标较小的，i对应的是后取出的，下标是较大的。</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                d[m] = i</span><br><span class="line">                </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">twoSum</span><span class="params">(self, nums: List[int], target: int)</span> -&gt; List[int]:</span></span><br><span class="line">        d = &#123;&#125;</span><br><span class="line">        <span class="keyword">for</span> i, m <span class="keyword">in</span> enumerate(nums):</span><br><span class="line">            n = target - m</span><br><span class="line">            <span class="keyword">if</span> n <span class="keyword">in</span> d.values():</span><br><span class="line">                <span class="keyword">return</span> [list(d.keys())[list(d.values()).index(n)], i] </span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                d[i] = m</span><br></pre></td></tr></table></figure>
<p>这种方法同样存在一个问题，由于字典中的键是不能重复的，如果像上面这样写，d[m] = i，则又是将元素m作为了键，下标作为了对应的值，一旦出现数组中有相同的元素的情况，就会导致计算错误或计算结果与其他方法不一致。如nums = [3, 3, 4, 4, 5]和target = 9时。受方法二时的影响，我们将下标作为键，元素m作为与下标对应的值，通过if n in d.values():判断n是否在d中，然后通过list(d.values()).index(n)定位n的下标，再通过list(d.keys())[]找到n对应的键。</p>
<h4 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">nums = [<span class="number">3</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">4</span>, <span class="number">5</span>]</span><br><span class="line">target = <span class="number">9</span></span><br><span class="line">c = Solution()</span><br><span class="line">x = c.twoSum(nums, target)</span><br><span class="line"><span class="keyword">print</span> (x)</span><br></pre></td></tr></table></figure>
<p>注：此题的代码均未考虑无解的情况。</p>

          
        
      
    </div>

    

    
    
    
	
	
	<div>
		
	</div>
	
    

    
      
    
    

    

    <footer class="post-footer">
		<div>    
			
			
		</div>
	
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
  </section>

  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/4/"><i class="fa fa-angle-left" aria-label="Previous page"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/4/">4</a><span class="page-number current">5</span><a class="page-number" href="/page/6/">6</a><span class="space">&hellip;</span><a class="page-number" href="/page/9/">9</a><a class="extend next" rel="next" href="/page/6/"><i class="fa fa-angle-right" aria-label="Next page"></i></a>
  </nav>



          </div>
          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <div class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/touxiang.jpg" alt="贾 添 植">
            
              <p class="site-author-name" itemprop="name">贾 添 植</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/blogs/">
                
                    <span class="site-state-item-count">9</span>
                    <span class="site-state-item-name">Blogs</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">Categories</span>
                  </a>
                </div>
              

              
            </nav>
          

          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                  
                    
                  
                  <a href="https://github.com/jiatianzhi" title="GitHub &rarr; https://github.com/jiatianzhi" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i></a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                  
                    
                  
                  <a href="mailto:jiatianzhi@bjtu.edu.cn" title="E-Mail &rarr; mailto:jiatianzhi@bjtu.edu.cn" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i></a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                  
                    
                  
                  <a href="https://jiatianzhi.blog.csdn.net" title="CSDN &rarr; https://jiatianzhi.blog.csdn.net" rel="noopener" target="_blank"><i class="fa fa-fw fa-copyright"></i></a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                  
                    
                  
                  <a href="https://www.zhihu.com/people/jiatianzhi" title="知乎 &rarr; https://www.zhihu.com/people/jiatianzhi" rel="noopener" target="_blank"><i class="fa fa-fw fa-question-circle"></i></a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                  
                    
                  
                  <a href="https://weibo.com/jiatianzhi" title="Weibo &rarr; https://weibo.com/jiatianzhi" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i></a>
                </span>
              
            </div>
          

          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Friends
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://xinfu607.github.io" title="https://xinfu607.github.io" rel="noopener" target="_blank">Xin Fu's HomePage</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.hljwkwm.com" title="https://www.hljwkwm.com" rel="noopener" target="_blank">Miao Wang's Homepage</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://shaun2016.github.io" title="https://shaun2016.github.io" rel="noopener" target="_blank">Jiaming Zhang's Homepage</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.ccf.org.cn" title="https://www.ccf.org.cn" rel="noopener" target="_blank">中国计算机学会</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.csig.org.cn" title="http://www.csig.org.cn" rel="noopener" target="_blank">中国图象图形学会</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </div>

      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tianzhi Jia</span>

  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.1"></script>

  <script src="/js/motion.js?v=7.1.1"></script>



  
  


  <script src="/js/affix.js?v=7.1.1"></script>

  <script src="/js/schemes/pisces.js?v=7.1.1"></script>




  

  


  <script src="/js/next-boot.js?v=7.1.1"></script>


  

  

  

  



  




  

  

  

  

  

  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>


  

  

  

  

  

  
<script>
  $('.highlight').not('.gist .highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('Copy').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('Copied');
        else $(this).text('Copy failed');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('Copy');
      }, 300);
    }).append(e);
  })
</script>


  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"enable":true,"scale":1,"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"superSample":2,"width":240,"height":240,"position":"right","hOffset":30,"vOffset":30},"mobile":{"show":false,"scale":0.5},"react":{"opacityDefault":0.7,"opacityOnHover":0.2,"opacity":0.7},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/click.js"></script>
